<template>
    <div>
        <Row style="margin:5px 0px 10px 5px" >
            <i-col span="2" >
                <Button  size="default"  type="primary" @click="btn_refresh">刷新</Button>
            </i-col>
		</Row>
        <i-table size="default"   border stripe  :columns="format" :data="show_list" :height="sharedState.tableHeight" >
            <template slot-scope="{ row, index }" slot="action">
                <Dropdown>
                    <a href="javascript:void(0)">
                        <Icon type="ios-create-outline" size="30" />
                    </a>
                    <DropdownMenu slot="list" placement="top-end">
                        <DropdownItem><Button  size="default"     @click="update_hpa_replica(index)">更新hpa</Button></DropdownItem>
                        <DropdownItem><Button  size="default"     @click="del_hpa(index)">删除</Button></DropdownItem>
                    </DropdownMenu>
                </Dropdown>

            </template>
        </i-table >
        <div style="text-align: center;margin-top: 10px;">
            <Page ref="page" :total="total" :page-size="pageSize"  @on-change="changePage" show-total/>
        </div>
        <!-- 更新副本模态框 -->
        <Modal v-model="show_update_hpa_replicas_modal" width="600">
            <p slot="header" style="color:#f60;text-align:center">
                {{namespace}}<span>更新hpa副本</span>
            </p>
            <div style="">
                <Form ref="hpa_replicas" :model="hpa_replicas" :rules="hpa_replicas_rules" label-position="left"  :label-width="150">
                    <Form-Item label="minReplicas:"  prop="minReplicas">
                        <Input type="number"  v-model="hpa_replicas.minReplicas" />
                    </Form-Item>
                    <Form-Item label="maxReplicas:"  prop="maxReplicas">
                        <Input type="number"  v-model="hpa_replicas.maxReplicas" />
                    </Form-Item>
                </Form> 
            </div>
            <div slot="footer">
                <Button  size="default"  type="primary"   @click="submit_update_hpa_replicas('hpa_replicas')">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import axios from 'axios';
import { 
get_hpa_list,
delete_hpa,
get_deployment_replicas,
update_hpa_replicas,
} from  '@/api'
import {k8s_namespace_post} from '@/api/http'
import { delete_namespace_resource } from  '@/common/util'
import store from '@/store'

export default {
    data() {
        const validateMinReplicas = (rule,value,callback) => {
            // console.log(typeof value)
            let minReplicas  = parseInt(value)
            if(minReplicas < 1) {
                callback(new Error('最小副本不能小于1'))
            }else{
                callback();
            }
        };
        const validateMaxReplicas = (rule,value,callback) => {
            // console.log(typeof value)
            let maxReplicas = parseInt(value)
            // console.log(maxReplicas,this.hpa_replicas.minReplicas)
            if(maxReplicas <this.replicas) {
                callback(new Error('最大副本不能小于当前副本'+this.replicas))
            }else if(maxReplicas < parseInt(this.hpa_replicas.minReplicas)){
                callback(new Error('最大副本不能小于最小副本'))
            }else if(maxReplicas > 10 ){
                callback(new Error('最大副本不能大于10'))
            }else{
                callback();
            }
        };
        return {
            sharedState: store.state,
            format: [
                {
                    title: '名字',key: 'name',align: 'center',width: 150,
                },
                {
                    title: '命名空间',key: 'namespace',align: 'center',width: 150,
                },
                {
                    title: '最小副本',key: 'minReplicas',align: 'center',width: 150,
                },
                {
                    title: '最大副本',key: 'maxReplicas',align: 'center',width: 150,
                },
                {
                    title: '扩展目标',key: 'scaleTargetRef',align:'center',width: 350,
                    render: (h, params) => {
                        return h('div', [
                            h('pre', JSON.stringify(params.row.scaleTargetRef,undefined,4))
                        ]);
                    }
                },
                {
                    title: '目标CPU占用百分比',key: 'targetCPUUtilizationPercentage',align: 'center',width: 250,
                },
                {
                    title: '操作',slot: 'action',align: 'center',width: 150,fixed:'right',
                }
            ],

            // 更新hpa副本
            hpa_replicas: {
                minReplicas: 1,
                maxReplicas: 1,
            },
            namespace: '',
            hpa_name: '',
            replicas: 1,
            hpa_replicas_rules:{
                minReplicas: [
                     { validator: validateMinReplicas,trigger: 'blur'},
                ],
                maxReplicas: [
                     { validator: validateMaxReplicas,trigger: 'blur'},
                ]
            },
            show_update_hpa_replicas_modal: false,
            // 分页
            total_list: [],
            show_list: [],
            // 分页
            total: 0,
            pageSize: 15,
        }
    },
    methods: {
        btn_refresh(){
            this.refresh()
        },
        changePage(index) {
            let _start = (index -1) * this.pageSize
            let _end = index * this.pageSize
            this.show_list = this.total_list.slice(_start,_end)
        },
        // 获取deployment的副本
        async get_deploy_replicas(namespace,name) {
            let cluster = localStorage.getItem('currentCluster')
            // let namespace = localStorage.getItem('currentNameSpace')
            let headers = {"cluster_name": cluster }
            let method='post'
            let url = get_deployment_replicas
            let data = {"namespace":namespace,"name":name}
            if(cluster){
                try {
                    let response = await axios({
                        url:url,headers:headers,data: data,method:method
                    })
                    // // console.log(response.data);
                    return response.data;
                } catch (error) {
                    console.error(error);
                    return null;
                }
            }
        },
        // 提交更新hpa副本事件
        submit_update_hpa_replicas(name){
            let validate = false
            this.$refs[name].validate((valid) => {
                if (valid) validate = true
            })
            if(!validate) return

            let data = {
                "name":this.hpa_name,
                "minReplicas":parseInt(this.hpa_replicas.minReplicas),
                "maxReplicas":parseInt(this.hpa_replicas.maxReplicas)
            }
            k8s_namespace_post(update_hpa_replicas,data).then(  (response) => {
                let info = JSON.stringify(response)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('更新hpa副本成功')
                    this.show_update_hpa_replicas_modal = false
                    this.refresh()
                }else {
                    alert(info)
                }
            })
        },
        async update_hpa_replica(index){
            
            let hpa_name = this.show_list[index].name
            this.hpa_name = hpa_name
            let current_min_replicas = this.show_list[index].minReplicas
            let current_max_replicas = this.show_list[index].maxReplicas
            this.hpa_replicas.minReplicas = current_min_replicas
            this.hpa_replicas.maxReplicas = current_max_replicas
            // console.log(current_min_replicas,current_max_replicas)

            let namespace = this.show_list[index].namespace
            // console.log("namespace",namespace)
            // console.log(this.show_list[index].scaleTargetRef.name)
            this.namespace = namespace
            let deploy_name  = this.show_list[index].scaleTargetRef.name

            // 获取副本数
            let result = await this.get_deploy_replicas(namespace,deploy_name)
            this.replicas = result.replicas
            // console.log("replicas:",replicas)
            this.show_update_hpa_replicas_modal = true

            
        },
        del_hpa(index){
            let name = this.show_list[index].name
            let result = confirm("确定要删除"+name+"吗?")
            if(result == false) return 
            let namespace = this.show_list[index].namespace
            delete_namespace_resource(namespace,name,delete_hpa)
            this.refresh()
        },
        refresh() {
            k8s_namespace_post(get_hpa_list).then( (response) => {
                this.total_list = response.data
                this.total = response.data.length
                if(this.total < this.pageSize) {
                    this.show_list = this.total_list
                }else {
                    // 修改改数据之后显示回到第一页的bug，改为停留在当前页
                    let currentPage = this.$refs.page.currentPage
                    let _start = (currentPage-1) * this.pageSize
                    let _end = currentPage * this.pageSize
                    this.show_list = this.total_list.slice(_start,_end)
                }
            })
        }
    },
    mounted: function() {
        setTimeout(() =>{
            this.refresh();
        },200); 
    }
}
</script>
<style scoped>

</style>